// pages/me/index.js
import util from '../../utils/utils';
import User from "../../utils/user";
import Data from "../../utils/data";
import {
  UserHttp
} from '../../api/user.js'
import Dialog from "../../dist/dialog/dialog";
const userHttp = new UserHttp();
let _token = util.token;
Page({
  /**
   * 页面的初始数据
   */
  isTabBar: true,
  showSet: false,
  tabIndex: 0,
  initStatus: false,
  data: {
    initUser: !!_token,
    new_msg: false,
    levelName: '普通会员',
    kryBlance: 0,
    userInfo: {
      common: {
        coupon_count: 0,
        card_blance: 0,
        pea_blance: 0,
        pea_blance_big:0,
      },
      complete_newquest: false
    },
    taskPage: {
      "name": "任务大厅",
      "path": '/pages/task/index',
      "version": 1
    },
    helpPage: {
      "name": "常见问题",
      "path": util.pageUrl + "H5/commonProblem/index.html",
      "version": 1
    },
    memberCenter: {
      "name": "会员中心",
      "path": util.pageUrl + "h5pages/memberCenter.html",
      "downUrl": "",
      "version": 1
    },
    taskBanner: {
      "name": "新手任务",
      "path": '/pages/task/index',
      "imgUrl": "https://img.quzhao.com/uploads/oss/images/banner/201912093932236733.png",
    },
    token: '',
    homePath: '',
    isShowRecharge: false, // 是否显示充值弹出层
    isShowTips: false, //是否显示转移弹窗
    noticeList: [],
  },
  /**
   * 页面载入完成
   */
  initPage: function(options) {
    let self = this;
    let app = getApp();
    wx.showTabBar();
    wx.hideShareMenu();
    self.initData(false);
    app.addEvent('upUserInfo', function(userInfo) {
      console.log('upUserInfo1',userInfo);
      userInfo['tuan'] = {};
      if (JSON.stringify(userInfo) !== JSON.stringify(self.data.userInfo)) {
        util.log('upUserInfo2',userInfo);
        if (!userInfo.uid) {
          self.setData({
            userInfo: {
              common: {
                coupon_count: 0,
                card_blance: 0,
                pea_blance: 0,
              },
            },
            initUser: false
          });
        } else {
          self.setData({
            userInfo: userInfo,
            initUser: true
          });
        }
      }
    });
    if(options.hasOwnProperty('ekey')){
      User.UvTrackPut(options.ekey);
    }
  },
  onShow: function() {
    util.closeLoading();
    let flag = true;
    this.tabIndex += 1;
    if (this.tabIndex > 1) {
      flag = true;
      this.tabIndex = 0;
    }
    if (this.initStatus === true) {
      this.initData(flag);
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    if (this.data.initUser !== true) {
      wx.stopPullDownRefresh();
      return false;
    }
    Data.getDictConfig('pageConfig', false, true);
    this.initData(true);
  },
  initData: function(ref) {
    let self = this;
    let app = getApp();
    let update = ref || false;
    console.log('initData',update);
    wx.showNavigationBarLoading();
    /**
     * 拉取基础数据资源
     */
    self.getUserInfo(function(result) {

      self.initStatus = true;
      if (result.hasOwnProperty('tuan')) {
        result['tuan']['money_text'] = util.formatMoney(result['tuan']['money_blance']);
        result['tuan']['month_text'] = util.formatMoney(result['tuan']['month_income']);
        result['tuan']['today_text'] = util.formatMoney(result['tuan']['today_income']);
      }
      result['levelName'] = User.getUserLevelTag(result);
      if (result.hasOwnProperty('parrent')) {
        result['parrent']['areaInfo'] = util.formatAreaToString(result['parrent']);
      }
      util.log('userinfo', result);

      self.setData({
        levelName: result.levelName,
        initUser: true,
        userInfo: result,
        token: util.token
      });
      /**
       * 获取页面配置
       */
      if (app.globalData.pageConfig.helpPage) {
        self.setData({
          helpPage: app.globalData.pageConfig.helpPage
        });
      }
      if (app.globalData.pageConfig.memberCenter) {
        self.setData({
          memberCenter: app.globalData.pageConfig.memberCenter
        });
      }
      //获取分享图片
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, function(res) {
      self.initStatus = true;
      self.setData({
        userInfo: {
          order_count: 0,
          common: {
            pea_blance: 0,
            month_pea_income: 0,
            today_pea_income: 0,
            pea_text: 0,
          }
        },
        initUser: false,
      });
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, update);
    
  },
  toTaskPage(event){
    let page = event.currentTarget.dataset.page;
    wx.switchTab({
      url:page
    })
  },
  toPage: function(event) {
    let login = true;
    if (event.currentTarget.dataset.login) {
      login = event.currentTarget.dataset.login;
    }
    if (this.data.initUser === false && login === "true") {
      util.msg('需要登录后才能操作哦!');
      return false;
    }
    util.toPage(event);
  },
  quickLogin: function(event) {
    let self = this;
    let userInfo = event.detail;
    if (userInfo.errMsg !== 'getUserInfo:ok') {
      util.msg('您取消了登录授权！');
    } else {
      util.loading('快捷登录中...');
      User.UserLogin(function(res) {
        util.closeLoading();
        self.userInfo = res;
        self.initUser = true;
        self.setData({
          initUser: true,
          userInfo: res
        });
        self.initData(true);
      }, function(res) {
        util.msg('登录失败.请稍候再试-001!');
      }, userInfo);
    }
  },
  // 开通会员
  onOpenMember() {
    //跳转到充值页面
    if (this.data.userInfo) {
      if (this.data.userInfo.common.card_payed === true) {
        util.toPage('/pages/index/me/charge/index?type=2');
      } else {
        util.toPage({
          currentTarget: {
            dataset: {
              page: this.data.memberCenter.path,
              title: "会员中心"
            }
          }
        });
      }
    }
  },
  // 关闭充值弹出层
  onCloseRecharge() {
    this.setData({
      isShowRecharge: false
    });
    User.getUserInfoByNet();
  },
});
